package jp.co.withone.osgi.gadget.pictureviewer.impl;

import java.util.TimerTask;

import jp.co.withone.osgi.gadget.pictureviewer.PictureController;

import org.osgi.util.tracker.ServiceTracker;

/**
 * PictureControlTask class provide picture main view repaint.
 * 
 * @author funakky
 */
public class PictureControlTask extends TimerTask {

	private final PictureViewerMainView viewer;

	private final ServiceTracker tracker;

	/**
	 * Create new PictureControlTask class.
	 * 
	 * @param viewer
	 *            main view
	 * @param tracker
	 *            tracking PictureController service
	 */
	public PictureControlTask(final PictureViewerMainView viewer,
			final ServiceTracker tracker) {
		this.viewer = viewer;
		this.tracker = tracker;
	}

	/**
	 * Repaint main view.
	 * 
	 * @see java.util.TimerTask#run()
	 */
	@Override
	public void run() {
		final PictureController controller = (PictureController) tracker
				.getService();
		if (controller == null) {
			this.viewer.setVisible(false);
			return;
		}
		final byte[] picture = controller.getPicture();
		if (picture == null) {
			this.viewer.setVisible(false);
			return;
		}
		this.viewer.setPicture(picture);
		this.viewer.repaint();
		if (!this.viewer.isVisible()) {
			this.viewer.setVisible(true);
		}
	}

}
